<template>
  <div class="user-search" v-if="isQuery">
    <el-form
      :label-width="searchConfig.labelWidth ?? '80px'"
      :model="searchForm"
      ref="formRef"
      size="large"
    >
      <el-row :gutter="120">
        <template v-for="item in searchConfig.formItems" :key="item.prop">
          <el-col :span="8">
            <el-form-item :label="item.label" :prop="item.prop">
              <template v-if="item.type === 'input'">
                <el-input v-model="searchForm[item.prop]" :placeholder="item.placeholder" />
              </template>

              <template v-if="item.type === 'date-picker'">
                <el-date-picker
                  v-model="searchForm[item.prop]"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                />
              </template>

              <template v-if="item.type === 'select'">
                <el-select
                  v-model="searchForm[item.prop]"
                  :placeholder="item.placeholder"
                  style="width: 100%"
                >
                  <template v-for="option in item.options" :key="option.value">
                    <el-option :label="option.label" :value="option.value" />
                  </template>
                </el-select>
              </template>
            </el-form-item>
          </el-col>
        </template>
      </el-row>
    </el-form>

    <!-- 2.重置和搜索的按钮 -->
    <div class="btns">
      <el-button icon="Refresh" @click="handleResetClick">重置</el-button>
      <el-button icon="Search" type="primary" @click="handleQueryClick">查询</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { ElForm } from 'element-plus'

import usePermissions from '@/hooks/usePermissions'

// 定义自定义事件
const emit = defineEmits(['queryClick', 'resetClick'])
// 定义接收的属性
interface IProps {
  pageName?: string
  searchConfig: {
    labelWidth?: string
    formItems: any[]
  }
}
const props = defineProps<IProps>()

const isQuery = usePermissions(`${props.pageName}:query`)

// 定义表单数据
const initailForm: any = {}
for (const item of props.searchConfig.formItems) {
  initailForm[item.prop] = item.initailValue ?? ''
}

const searchForm = reactive(initailForm)

// 重置操作
const formRef = ref<InstanceType<typeof ElForm>>()
function handleResetClick() {
  // 将数据进行重置
  formRef.value?.resetFields()

  // 将时间传递给父组件,通过父组件重新发送网络请求
  emit('resetClick')
}
// 查询操作
function handleQueryClick() {
  // 向父组件发送事件，在父组件上监听
  emit('queryClick', searchForm)
}
</script>

<style lang="less" scoped>
.user-search {
  padding: 20px 30px 0 10px;
  background-color: #fff;

  .btns {
    text-align: right;
    padding: 0 5px 10px 0;

    .el-button {
      height: 36px;
    }
  }
}
</style>
